package com.dz.server.controller;


import com.dz.server.mapper.ProductAtomicMapper;
import com.dz.server.pojo.Atomic;
import com.dz.server.pojo.Product;
import com.dz.server.pojo.ProductAtomic;
import com.dz.server.service.AtomicService;
import com.dz.server.service.ProductAtomicService;
import com.dz.server.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dz
 * @since 2022-03-23
 */
@Controller
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private AtomicService atomicService;
    @Autowired
    private ProductAtomicService productAtomicService;

    private Product product;
    //跳转到添加产品页面
    @RequestMapping("/toAddProduct")
    public String toAdd(){
        return "server/add-product";
    }
    //去产品详情展示页
    @RequestMapping("/toShowProduct{productId}")
    public String toShowProduct(@PathVariable("productId")Integer id,Model model){
        Product product = productService.getById(id);
        model.addAttribute("product",product);
        String atomics = productService.getAtomics(id);
        model.addAttribute("atomics",atomics);
        return "server/show-product";
    }
    //去修改产品界面
    @RequestMapping("/toUpdateProduct{productId}")
    public String toUpdateProduct(@PathVariable("productId")Integer id,Model model){
        Product product = productService.getById(id);
        model.addAttribute("product",product);
        return "server/update-product";
    }
    @RequestMapping("/toUpdateAtomic")
    public String updateProduct(Product product,Model model){
        this.product = product;
        List<Atomic> atomics = atomicService.list();
        model.addAttribute("atomics",atomics);
        return "server/update-atomic";
    }
    @RequestMapping("/updateProduct")
    public String updateProduct(String msg){
        //修改产品内容
        productService.updateById(product);
        //修改原子服务（先删除，再添加）
        productAtomicService.deleteAtomicByProductId(product.getId());
        List<Atomic> atomics = atomicService.getAtomics(msg);
        for (Atomic atomic : atomics) {
            ProductAtomic productAtomic = new ProductAtomic(product.getId(), atomic.getId());
            productAtomicService.save(productAtomic);
        }
        return "redirect:/toIndex";
    }
}

